package net.lesscoding.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.entity.account.AccountTbl;
import net.lesscoding.mapper.AccountMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author eleven
 * @date 2025/4/16 14:21
 * @apiNote
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AccountService extends ServiceImpl<AccountMapper, AccountTbl> {

    private final AccountMapper accountMapper;

    @Transactional
    public Integer deduct(String userId, BigDecimal money) {
        AccountTbl accountTbl = accountMapper.selectOne(new LambdaQueryWrapper<AccountTbl>()
                .eq(AccountTbl::getUserId, userId));
        if (accountTbl == null) {
            throw  new RuntimeException("用户id不存在");
        }
        if (accountTbl.getMoney().compareTo(money) < 0) {
            throw new RuntimeException("余额不足");
        }
        log.info("扣款成功");
        return accountMapper.deduct(userId, money);
    }
}
